<template>
  <view class="container">

    <!-- 表单 -->
    <view class="form-container">
      <!-- 照片上传 -->
      <view class="photo-section">
        <view class="photo-title">宠物照片</view>
        <view class="photo-upload" @click="choosePhoto">
          <image 
            v-if="formData.photo" 
            :src="formData.photo" 
            class="uploaded-photo" 
            mode="aspectFill"
          ></image>
          <view v-else class="upload-placeholder">
            <text class="upload-icon">📷</text>
            <text class="upload-text">点击上传照片</text>
          </view>
        </view>
      </view>

      <!-- 基本信息 -->
      <view class="form-section">
        <view class="form-item">
          <text class="label">宠物名称 <text class="required">*</text></text>
          <input 
            v-model="formData.name" 
            placeholder="请输入宠物名称" 
            class="input"
            maxlength="50"
          />
        </view>

        <view class="form-item">
          <text class="label">宠物类型 <text class="required">*</text></text>
          <picker 
            :value="typeIndex" 
            :range="petTypeLabels" 
            @change="onTypeChange"
            class="picker"
          >
            <view class="picker-text">
              {{ formData.type || '请选择宠物类型' }}
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">品种 <text class="required">*</text></text>
          <input 
            v-model="formData.breed" 
            placeholder="请输入品种" 
            class="input"
            maxlength="20"
          />
        </view>

        <view class="form-item">
          <text class="label">性别 <text class="required">*</text></text>
          <picker 
            :value="genderIndex" 
            :range="genderLabels" 
            @change="onGenderChange"
            class="picker"
          >
            <view class="picker-text">
              {{ formData.gender || '请选择性别' }}
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">生日 <text class="required">*</text></text>
          <picker 
            mode="date" 
            :value="formData.birthday" 
            @change="onBirthdayChange"
            class="picker"
          >
            <view class="picker-text">
              {{ formData.birthday || '请选择生日' }}
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">体重 (kg)</text>
          <input 
            v-model="formData.weight" 
            placeholder="请输入体重" 
            class="input"
            type="digit"
            maxlength="5"
          />
        </view>

        <view class="form-item">
          <text class="label">颜色</text>
          <input 
            v-model="formData.color" 
            placeholder="请输入颜色" 
            class="input"
            maxlength="20"
          />
        </view>

        <view class="form-item">
          <text class="label">备注</text>
          <textarea 
            v-model="formData.remark" 
            placeholder="请输入备注信息" 
            class="textarea"
            maxlength="200"
          />
        </view>
      </view>
    </view>
    
    <!-- 底部保存按钮 -->
    <view class="bottom-save-section">
      <button class="bottom-save-btn" @click="savePet" :disabled="loading">
        {{ loading ? '保存中...' : '保存' }}
      </button>
    </view>
  </view>
</template>

<script>
import { addPet, uploadPetPhoto } from '@/api/pet.js'
import { getUserId, checkAndRedirectToLogin, getToken } from '@/utils/auth.js'
import { getDictData } from '@/api/dict.js'
import { API_BASE } from '@/config/config.js'

export default {
  data() {
    return {
      loading: false,
      formData: {
        name: '',
        type: '',
        breed: '',
        gender: '',
        birthday: '',
        weight: '',
        color: '',
        photo: '',
        remark: ''
      },
      petTypes: [],
      genders: [],
      petTypeLabels: [],
      genderLabels: [],
      typeIndex: -1,
      genderIndex: -1,
    }
  },
  onLoad() {

    
    // 页面加载时检查登录状态
    if (!checkAndRedirectToLogin('请先登录')) {
      return
    }
    
    // 加载字典数据
    this.loadDictData()
  },
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    choosePhoto() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const localPath = res.tempFilePaths[0]
          // 先本地预览
          this.formData.photo = localPath
          // 上传到服务器
          this.uploadPetPhoto(localPath)
        }
      })
    },
    
    async uploadPetPhoto(filePath) {
      const token = getToken()
      if (!token) {
        uni.showToast({ title: '请先登录', icon: 'none' })
        uni.navigateTo({ url: '/pages/login?from=pet' })
        return
      }
      uni.showLoading({ title: '上传中...' })
      try {

        const data = await uploadPetPhoto(filePath, token)

        if (data && data.code === 200) {
          const photoUrl = data.photoUrl || (data.data && (data.data.photoUrl || data.data.url))
          if (photoUrl) {
            // 处理照片URL - 后端返回的是相对路径，需要拼接完整URL
            let finalPhotoUrl = photoUrl
            
            // 如果后端返回的是 /profile/upload/... 格式，拼接基础URL
            if (photoUrl.startsWith('/profile/')) {
              finalPhotoUrl = API_BASE + photoUrl
            } else if (photoUrl.startsWith('/')) {
              // 其他相对路径，拼接基础URL
              finalPhotoUrl = API_BASE + photoUrl
            } else if (!photoUrl.startsWith('http')) {
              // 文件名，拼接完整URL
              finalPhotoUrl = API_BASE + `/profile/upload/${photoUrl}`
            }
            

            
            // 更新表单数据
            this.formData.photo = finalPhotoUrl
            
            // 强制触发页面重新渲染
            this.$forceUpdate()
            
            // 延迟一下再显示成功提示，确保页面更新
            setTimeout(() => {
              uni.showToast({ title: '照片已上传', icon: 'success' })
            }, 100)
            
          } else {
            uni.showToast({ title: '上传成功但未返回地址', icon: 'none' })
          }
        } else {

          uni.showToast({ title: (data && data.msg) || '上传失败', icon: 'none' })
        }
      } catch (error) {

        // 检查是否是网络相关错误
        if (error.errMsg && error.errMsg.includes('fail')) {
          uni.showToast({ title: '网络错误，请检查网络连接', icon: 'none' })
        } else {
          uni.showToast({ title: '上传失败: ' + (error.message || error.errMsg || '未知错误'), icon: 'none' })
        }
      } finally {
        uni.hideLoading()
      }
    },
    
    onTypeChange(e) {
      this.typeIndex = e.detail.value
      this.formData.type = this.petTypes[e.detail.value].dictLabel
    },
    
    onGenderChange(e) {
      this.genderIndex = e.detail.value
      this.formData.gender = this.genders[e.detail.value].dictLabel
    },
    
    onBirthdayChange(e) {
      this.formData.birthday = e.detail.value
    },
    
    validateForm() {
      if (!this.formData.name.trim()) {
        uni.showToast({
          title: '请输入宠物名称',
          icon: 'none'
        })
        return false
      }
      if (!this.formData.type) {
        uni.showToast({
          title: '请选择宠物类型',
          icon: 'none'
        })
        return false
      }
      if (!this.formData.breed) {
        uni.showToast({
          title: '请输入品种',
          icon: 'none'
        })
        return false
      }
      if (!this.formData.gender) {
        uni.showToast({
          title: '请选择性别',
          icon: 'none'
        })
        return false
      }
      if (!this.formData.birthday) {
        uni.showToast({
          title: '请选择生日',
          icon: 'none'
        })
        return false
      }
      return true
    },
    
    async savePet() {
      if (!this.validateForm()) {
        return
      }
      

      
      // 检查登录状态
      if (!checkAndRedirectToLogin('请先登录')) {

        return
      }
      

      
      // 获取用户ID
      const userId = getUserId()

      if (!userId) {
        uni.showToast({
          title: '用户信息获取失败',
          icon: 'none'
        })
        return
      }
      
      this.loading = true
      uni.showLoading({
        title: '保存中...'
      })
      
      try {
        // 准备提交数据，确保字段名与后端实体类匹配
        const submitData = {
          name: this.formData.name,
          type: this.formData.type,
          breed: this.formData.breed,
          gender: this.formData.gender,
          birthday: this.formData.birthday,
          weight: this.formData.weight ? parseFloat(this.formData.weight) : null,
          color: this.formData.color,
          photo: this.formData.photo,
          remark: this.formData.remark,
          userId: userId,
          status: 'online'
        }
        
        // 使用专门的移动端API接口，避免权限问题
        const response = await addPet(submitData)
        
        uni.hideLoading()
        
        if (response.code === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: response.msg || '保存失败',
            icon: 'none'
          })
    
        }
      } catch (error) {
        uni.hideLoading()
  
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    async loadDictData() {
      try {
        // 加载宠物类型字典
        const petTypeResponse = await getDictData('pet_type')
        if (petTypeResponse && petTypeResponse.code === 200) {
          this.petTypes = petTypeResponse.data || [];
          this.petTypeLabels = this.petTypes.map(item => item.dictLabel);
         
        } else {
          // 默认值
          this.petTypes = [
            { dictLabel: '狗', dictValue: 'dog' },
            { dictLabel: '猫', dictValue: 'cat' },
            { dictLabel: '兔子', dictValue: 'rabbit' },
            { dictLabel: '鸟', dictValue: 'bird' },
            { dictLabel: '鱼', dictValue: 'fish' },
            { dictLabel: '其他', dictValue: 'other' }
          ]
          this.petTypeLabels = this.petTypes.map(item => item.dictLabel)
        }
        
        // 加载宠物性别字典
  
        const genderResponse = await getDictData('pet_gender')
  
        
        if (genderResponse && genderResponse.code === 200) {
          this.genders = genderResponse.data || [];
          this.genderLabels = this.genders.map(item => item.dictLabel);
          
        } else {
          
          // 默认值
          this.genders = [
            { dictLabel: '公', dictValue: 'male' },
            { dictLabel: '母', dictValue: 'female' }
          ]
          this.genderLabels = this.genders.map(item => item.dictLabel)
        }
        
        
        
      } catch (error) {
        
        // 使用默认值
        this.petTypes = [
          { dictLabel: '狗', dictValue: 'dog' },
          { dictLabel: '猫', dictValue: 'cat' },
          { dictLabel: '兔子', dictValue: 'rabbit' },
          { dictLabel: '鸟', dictValue: 'bird' },
          { dictLabel: '鱼', dictValue: 'fish' },
          { dictLabel: '其他', dictValue: 'other' }
        ]
        this.petTypeLabels = this.petTypes.map(item => item.dictLabel)
        this.genders = [
          { dictLabel: '公', dictValue: 'male' },
          { dictLabel: '母', dictValue: 'female' }
        ]
        this.genderLabels = this.genders.map(item => item.dictLabel)
      }
    }
  }
}
</script>

<style scoped>
.container {
  background: #f5f5f5;
  min-height: 100vh;
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.back-btn {
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 10rpx 30rpx;
  font-size: 28rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
}

.form-container {
  padding: 20rpx;
  padding-bottom: 120rpx; /* 为底部固定按钮留出空间 */
}

.photo-section {
  background: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.photo-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.photo-upload {
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #ddd;
  border-radius: 10rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.photo-upload:active {
  border-color: #007AFF;
  background: #f0f8ff;
}

.uploaded-photo {
  width: 100%;
  height: 100%;
  border-radius: 10rpx;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-icon {
  font-size: 60rpx;
  margin-bottom: 10rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #999;
}

.form-section {
  background: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.form-item {
  margin-bottom: 30rpx;
  display: flex;
  align-items: center;
}

.label {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  min-width: 160rpx;
  flex-shrink: 0;
}

.required {
  color: #ff4757;
  margin-left: 4rpx;
  font-weight: bold;
}

.input, .picker, .textarea {
  flex: 1;
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fff;
  margin-left: 20rpx;
}

.picker-text {
  color: #333;
  min-height: 44rpx;
  line-height: 44rpx;
  display: flex;
  align-items: center;
}

.textarea {
  height: 120rpx;
  resize: none;
}

.input:focus, .textarea:focus {
  border-color: #007AFF;
}

.bottom-save-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 20rpx;
  border-top: 1px solid #eee;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1);
}

.bottom-save-btn {
  width: 100%;
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 10rpx;
  padding: 25rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.bottom-save-btn:disabled {
  background: #ccc;
  color: #999;
}

.bottom-save-btn:active {
  background: #0056b3;
}
</style>